package com.my.lock.v6;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicSemaphore extends AtomicInteger {
    private static final Logger LOGGER = LoggerFactory.getLogger(AtomicSemaphore.class);

    private int max;

    public AtomicSemaphore(int max) {
        if (max <= 0) {
            throw new IllegalArgumentException();
        }
        set(max);
        this.max = max;
    }

    /**
     * @return 是 表示还未超过设置的最大值，可以继续增加
     * 否 表示已超过设置的最大值，不可以继续增加
     */
    public boolean increment() {
        return get() < this.max && compareAndSet(get(), get() + 1);
    }

    /**
     * @return 是 表示还未到达0，可以继续减少
     * 否 表示已低于或等于0，不可以继续减少
     */
    public boolean decrement() {
        return get() > 0 && compareAndSet(get(), get() - 1);
    }

    public static void main(String[] args) throws Exception {
        AtomicSemaphore semaphore = new AtomicSemaphore(5);

        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean increment = semaphore.increment();
                    LOGGER.info("semaphore: {}", increment);
                }
            });
            threads.add(thread);
            thread.start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        LOGGER.info("semaphore result: {}", semaphore);
    }
}
